package com.hnkywl.sts.webservice.bg.impl;

import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.jhgl.BgjhhzmxService;
import com.hnkywl.sts.webservice.bg.IPlanBack;
import com.hnkywl.sts.webservice.bg.request.PlanBack;
import com.hnkywl.sts.webservice.bg.util.ConstantBg;
import com.hnkywl.sts.webservice.bg.response.Response;
import com.hnkywl.sts.webservice.bg.util.StackTraceUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-5-21
 * Time: 下午9:15
 * To change this template use File | Settings | File Templates.
 */
@Service
public class PlanBackService implements IPlanBack, ApplicationContextAware {
    private ApplicationContext applicationContext;
    // 保供计划汇总明细service
    private BgjhhzmxService bgjhhzmxService;
    private WebserviceLogService webserviceLogService;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        bgjhhzmxService = (BgjhhzmxService) applicationContext.getBean("bgjhhzmxService");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    public Response doplanback(String planBackXml) {
        // 返回值
        Response res = new Response();
        String exception = "";
        List<PlanBack> planBackList = getPlanBacks(planBackXml);
        if (null == planBackList || planBackList.size() <= 0) {
            res.setRetCode(ConstantBg.LOSE_PARA);
            res.setRemark("缺失参数或者参数为空！");
        } else {
            // 进行数据处理，调用service里的方法
            try {
                String reslut = this.bgjhhzmxService.InterfacePlanBack(planBackList);
                if (null == reslut) {
                    res.setRetCode(ConstantBg.OPERATOR_ILLEGAL);
                    res.setRemark("数据操作异常！");
                } else {
                    res.setRetCode(ConstantBg.SYN_SUCCESS);
                    res.setRemark("数据同步成功！");
                }

            } catch (Exception e) {
                e.printStackTrace();
                exception = StackTraceUtil.getStackTrace(e);
                res.setRetCode(ConstantBg.DEAL_FAIL);
                res.setRemark("数据处理错误！");
            }
        }
        webserviceLogService.saveServerLog(
                PlanBackService.class.getName(),
                "doplanback",
                planBackXml,
                "返回代码：" + res.getRetCode() + "  说明：" + res.getRemark(),
                exception,
                ""
        );
        return res;
    }

    /**
     * 解析xml转化为list
     *
     * @param planBackXML
     * @return
     */
    private List<PlanBack> getPlanBacks(String planBackXML) {
        List<PlanBack> list = new ArrayList<PlanBack>();
        PlanBack planBack;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder;
            builder = factory.newDocumentBuilder();

            String encoded = "utf-8";
            if (planBackXML.indexOf("gb2312") != -1) {
                encoded = "gb2312";
            }
            Document doc = builder.parse(new ByteArrayInputStream(planBackXML.getBytes(encoded)));
            int nodeLength = doc.getElementsByTagName("planback").getLength();
            for (int i = 0; i < nodeLength; i++) {
                planBack = new PlanBack();
                String detailId = doc.getElementsByTagName("detailid").item(i).getFirstChild().getNodeValue();
                String stopflag = doc.getElementsByTagName("stopflag").item(i).getFirstChild().getNodeValue();
                String operator = doc.getElementsByTagName("operator").item(i).getFirstChild().getNodeValue();
                String reason = doc.getElementsByTagName("reason").item(i).getFirstChild().getNodeValue();
                planBack.setDetailId(Long.valueOf(detailId));
                planBack.setStopflag(stopflag);
                planBack.setReason(reason);
                planBack.setOperator(operator);
                list.add(planBack);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }
}
